import axios from "axios";

const request = axios.create({
   baseURL: import.meta.env.VITE_API_BASE_URL, // 需要配置环境变量
  timeout: 10000,
});

let isRefreshing = false;
let requests: ((token: string) => void)[] = []; // 更明确的类型定义

// 请求拦截器
request.interceptors.request.use(
  async (config) => {
    const token = localStorage.getItem("token");
    const expireTime = Number(localStorage.getItem("tokenExpire")) || 0;

    // Token有效期检查（提前30秒刷新）
    if (token && expireTime - Date.now() < 30000) {
      if (!isRefreshing) {
        isRefreshing = true;
        
        try {
          const newToken = await refreshTokenHandler();
          localStorage.setItem("token", newToken);
          localStorage.setItem("tokenExpire", (Date.now() + 3600 * 1000).toString());
          requests.forEach(cb => cb(newToken));
          requests = [];
        } catch (error) {
          handleRefreshError(error);
          throw error;
        } finally {
          isRefreshing = false;
        }
      }

      // 挂起当前请求
      return new Promise((resolve) => {
        requests.push((newToken: string) => {
          config.headers.Authorization = newToken;
          resolve(request(config));
        });
      });
    }

    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  error => Promise.reject(error)
);
//ctvuybiunm
// 响应拦截器
request.interceptors.response.use(
  response => response,
  async error => {
    const originalRequest = error.config;
    
    if (error.response?.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;
      
      try {
        const newToken = await refreshTokenHandler();
        localStorage.setItem("token", newToken);
        localStorage.setItem("tokenExpire", (Date.now() + 3600 * 1000).toString());
        
        originalRequest.headers.Authorization = newToken;
        return request(originalRequest);
      } catch (error) {
        handleRefreshError(error);
        return Promise.reject(error);
      }
    }
    return Promise.reject(error);
  }
);

// 刷新Token操作
async function refreshTokenHandler(): Promise<string> {
  const refreshToken = localStorage.getItem("refreshToken");
  if (!refreshToken) throw new Error("No refresh token");
  
  const res = await axios.post('/api/refreshToken', { refreshToken });
  
  if (res.data && res.data.accessToken) {
    return res.data.accessToken;
  }
  
  throw new Error("刷新Token失败");
}

// 处理刷新失败
function handleRefreshError(error: any) {
  console.error("刷新Token失败:", error);
  localStorage.removeItem("token");
  localStorage.removeItem("refreshToken");
  localStorage.removeItem("tokenExpire");
  localStorage.removeItem("userInfo");
  window.location.href = "/"; 
}

export default request;